import { ref, reactive, watch } from 'vue'

import { merchantService } from '@/api'

import type { AttrList, Child } from '@/type/merchant/goodsInfo'

import { useStore } from '@/store'

export function useSpecs() {
  const store = useStore()
  const sku = reactive({
    goodsId: '',
    check: [],
    defaultSku: {},
    list: [],
    defaultAttr: [] as Array<any>,
  })

  /**
   * 加载商品数据
   * @param goodsId
   * @returns
   */
  const initGoodsInfo = async (goodsId: string) => {
    return new Promise((resolve, reject) => {
      merchantService.getGoodsInfo(goodsId).then((res) => {
        sku.list = res.data.attrList as any
        sku.defaultSku = res.data.defaultSku
        sku.defaultAttr = res.data.defaultAttr
        resolve(sku)
      })
    })
  }

  const productSpecsRef = ref()
  const specs = reactive({
    popupShow: false,
    productInfo: [],
  })

  /**
   * 打开规格弹窗
   * @param item
   */
  const selectSpecsHandle = (item: any) => {
    sku.goodsId = item.goodsId
    initGoodsInfo(item.goodsId).then((res: any) => {
      productSpecsRef.value.open()
    })
  }

  /**
   * 商品参数选择
   * @param itemList
   * @param data
   */
  const selectItemHandle = async (itemList: Array<Child>, data: AttrList) => {
    //拼接sku标记
    let mark = sku.goodsId
    itemList.forEach((v) => {
      mark += ',' + v.attrId + ':' + v.id
    })
    merchantService.byAttrGetSkuInfo(mark).then((res) => {
      sku.defaultSku = res.data
    })
  }

  /**
   * 规格弹窗点击选好了商品
   * @param itemList 选择的规格组合
   * @param goodsNumber 购买数量
   */
  const submitSelectHandle = (itemList: Array<Child>, goodsNumber: number) => {
    let mark = sku.goodsId
    itemList.forEach((v) => {
      mark += ',' + v.attrId + ':' + v.id
    })

    merchantService.byAttrGetSkuInfo(mark).then((res) => {
      let state = true
      store.useOrderStore.selectGoods.forEach((v, i) => {
        if (v.key === mark) {
          store.useOrderStore.selectGoods[i] = {
            key: mark,
            goodsId: sku.goodsId,
            skuInfo: res.data,
            skuItem: itemList,
            number: goodsNumber,
          }
          state = false
        }
      })

      if (state) {
        store.useOrderStore.addGoods({
          key: mark,
          goodsId: sku.goodsId,
          skuInfo: res.data,
          skuItem: itemList,
          number: goodsNumber,
        })
      }
      productSpecsRef.value.close()
      console.log(store.useOrderStore.selectGoods, 666666666)
    })
  }

  return {
    specs,
    sku,
    productSpecsRef,
    selectSpecsHandle,
    selectItemHandle,
    submitSelectHandle,
  }
}
